import 'dart:async';

import 'package:enterprise_v6_app/app/components/toast_widget.dart';
import 'package:enterprise_v6_app/app/core/core.dart';
import 'package:enterprise_v6_app/app/core/http/http.dart';
import 'package:enterprise_v6_app/app/core/utils/custom_event_bus.dart';
import 'package:enterprise_v6_app/app/core/utils/interface.dart';
import 'package:enterprise_v6_app/app/data/entities/application/education/couser_center/get_text_book_setting_entity.dart';
import 'package:enterprise_v6_app/app/data/entities/application/education/couser_center/list_by_book_id_entity.dart';
import 'package:enterprise_v6_app/app/data/entities/application/education/couser_center/list_question_by_book_id_entity.dart';
import 'package:enterprise_v6_app/app/modules/application/education/course_center/integrated_theme/course_detail_detail_page/course_detail/course_detail_controller.dart';
import 'package:enterprise_v6_app/app/modules/application/education/quiz/model.dart';
import 'package:enterprise_v6_app/app/modules/auth/face/model.dart';
import 'package:enterprise_v6_app/router/app_pages.dart';
import 'package:get/get.dart';

///课程目录directory
class TrainDirectoryController extends GetxController {
  ///根据课程查询目录列表
  List<ListByBookIdEntity>? listByBookIdEntity = [];

  ///根据课程查询试题列表
  List<ListQuestionByBookIdEntity>? listQuestionByBookIdEntity = [];

  ///查询课程设置  考试时长 和是否人脸识别了（isPersonIdentify）
  GetTextBookSettingEntity? getTextBookSettingEntity;
  StreamSubscription<MyEntity>? eventSubscription;

  @override
  void onInit() {
    super.onInit();
    //根据课程查询目录列表
    listByBookId();
    //查询课程设置(考试时长)
    getTextBookSetting();
    //根据课程查询试题列表
    listQuestionByBookId();

    //接受事件
    eventSubscription = CustomEventBus.getInstance().on<MyEntity>().listen((event) {
      if (event.type == MyEntity.TYPEPAGEREFASH) {
        //根据课程查询目录列表
        listByBookId();
      }
    });
  }

  @override
  void onClose() {
    super.onClose();
    //取消EventBus事件订阅，防止内存泄漏。
    eventSubscription?.cancel();
  }

  ///根据课程查询目录列表
  void listByBookId() async {
    final res = await HttpUtil().generateGetRequest<List<ListByBookIdEntity>>(
      Interface.listByBookId,
      queryParameters: {
        'bookId': Get.arguments['id'],
      },
    ).execute();
    res.onSuccess((result) {
      if (result.data != null) {
        listByBookIdEntity = result.data!;
        update();
      }
    });
  }

  ///根据课程查询试题列表
  void listQuestionByBookId() async {
    final res = await HttpUtil().generateGetRequest<List<ListQuestionByBookIdEntity>>(
      Interface.listQuestionByBookId,
      queryParameters: {
        'id': Get.arguments['id'],
      },
    ).execute();
    res.onSuccess((result) {
      if (result.data != null) {
        listQuestionByBookIdEntity = result.data!;
        update();
      }
    });
  }


  //开始做题
  void startDoingQuestions() {
    final bool isFace = _faceBool();
    if (isFace) {
      _inPage();
      return;
    }
    //先进行人脸识别--在进行答题
    Get.toNamed(AppRoutes.faceAuth, arguments: {
      'type': FaceAuthType.recog, // 识别类型
    })?.then((value) {
      /// 从此页面返回，会返回一个 bool?
      /// - true：成功
      /// - false：失败
      /// - null：未识别
      if (value == true) {
       _inPage();
      } else if (value == false) {
        AppToast.showWarning('人脸识别失败');
      } else {
        AppToast.showWarning('未识别');
      }
    });
  }

  //练习记录
  void practiceRecords() {
    Get.toNamed(AppRoutes.quizHistoryPage, arguments: Get.arguments['id']);
  }

  /// 进行人脸识别      idDirectoryFile目录里的列表id、判断是否被点击了
  void faceConfirm(String? directoryFile, String? idDirectoryFile) {
    final bool isFace = _faceBool();
    if (isFace) {
      //直接进入详情
      Get.toNamed(AppRoutes.courseDetailDetailPage, arguments: {
        'id': Get.arguments['id'],
        'idDirectoryFile': idDirectoryFile ?? '',
        'directoryFile': directoryFile ?? '',
        'planId': Get.find<CourseDetailController>().planId,
      });
      return;
    }
    Get.toNamed(AppRoutes.faceAuth, arguments: {
      // 'personId': 'test', // 人员ID
      'type': FaceAuthType.recog, // 识别类型
    })?.then((value) {
      // 从此页面返回，会返回一个 bool?
      // - true：成功
      // - false：失败
      // - null：未识别
      if (value == true) {
        Get.toNamed(AppRoutes.courseDetailDetailPage, arguments: {
          'id': Get.arguments['id'],
          'idDirectoryFile': idDirectoryFile ?? '',
          'directoryFile': directoryFile ?? '',
          'planId': Get.find<CourseDetailController>().planId,
        });
      } else if (value == false) {
        AppToast.showWarning('人脸识别失败');
      } else {
        AppToast.showWarning('未识别');
      }
    });
  }

  //查询课程设置(考试时长)
  void getTextBookSetting() async {
    final res = await HttpUtil().generateGetRequest<GetTextBookSettingEntity>(
      Interface.getTextBookSetting,
      queryParameters: {
        'textbookId': Get.arguments['id'],
      },
    ).execute();
    res.onSuccess((result) {
      if (result.data != null) {
        getTextBookSettingEntity = result.data!;
      }
    });
  }

  /// 是否进行了人脸识别
  bool _faceBool() {
    if (getTextBookSettingEntity?.isPersonIdentify != null && getTextBookSettingEntity?.isPersonIdentify == 0) {
      //是否进行实人验证  //0：人脸识别
      return true;
    }
    return false;
  }

  void addCourseWatchRecordK(int? totalDurationInSeconds, int? currentPositionDurationInSeconds, String? directoryFileIdCurrent) async {
    final res = await HttpUtil().generatePostRequest(Interface.addCourseWatchRecord, data: {
      'textbookId': Get.arguments['id'], //	课程id
      'totalDuration': totalDurationInSeconds, //总时长
      'deadline': currentPositionDurationInSeconds, //截至时间(观看进度)
      'directoryId': directoryFileIdCurrent, //课程目录id（当前id）
      'planId': Get.find<CourseDetailController>().planId, //计划id (上上个界面传入)
    }).execute();
    res.onSuccess((result) {
      //当前需要id 判断id是否选中
      listByBookId2(directoryFileIdCurrent);
      //刷新界面
      CustomEventBus.getInstance().fire(MyEntity(MyEntity.TYPGETPLANBYTEXTBOOKID, ''));
    });
  }

  ///根据课程查询目录列表 目录--》选中状态修改
  void listByBookId2(String? idDirectoryFile) async {
    final res = await HttpUtil().generateGetRequest<List<ListByBookIdEntity>>(
      Interface.listByBookId,
      queryParameters: {
        'bookId': Get.arguments['id'],
      },
    ).execute();
    res.onSuccess((result) {
      if (result.data != null) {
        listByBookIdEntity = result.data!;
        for (var directoryFile in listByBookIdEntity!) {
          if (idDirectoryFile != null) {
            if (directoryFile.id == idDirectoryFile) {
              //设置选中
              directoryFile.click = true;
            }
          }
        }
        update();
      }
    });
  }
  void _inPage() {
    final List<QuizTopic> topicsX = [];
    for (var listEntity in listQuestionByBookIdEntity!) {
      List<int>? answersX = [];
      final List<String> optionsX = [];
      if (listEntity.optionA != null) {
        optionsX.add('${listEntity.optionA}');
      }
      if (listEntity.optionB != null) {
        optionsX.add('${listEntity.optionB}');
      }
      if (listEntity.optionC != null) {
        optionsX.add('${listEntity.optionC}');
      }
      if (listEntity.optionD != null) {
        optionsX.add('${listEntity.optionD}');
      }
      //转码-对应的65 得到0的角标 A(65)-65=0
      answersX = listEntity.questionValidity?.split(';').map((e) => e.codeUnitAt(0) - 65).toList();
      topicsX.add(QuizTopic(
        id: listEntity.id ?? '',
        question: '${listEntity.questionMain}',
        answers: answersX,
        options: optionsX,
        score: listEntity.score ?? 0,
      ));
    }
    if (topicsX.isEmpty) {
      AppToast.showWarning('没有题目~');
      return;
    }
    Get.toNamed(AppRoutes.quizPage,
        arguments: QuizConfig(
          textbookId: Get.arguments['id'] as String,
          planId: Get.find<CourseDetailController>().planId,
          type: QuizType.lessonTest,
          topics: topicsX,
          leftSeconds: getTextBookSettingEntity?.duration != null ? getTextBookSettingEntity!.duration! * 60 : 60,
        ));
  }
}
